package com.controller;

import java.io.File;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Record;
import com.entity.Scope;
import com.entity.Subject;
import com.entity.Sysuser;
import com.server.SubjectServer;
import com.server.ClazzServer;
import com.server.CourseServer;
import com.server.PtypeServer;
import com.server.RecordServer;
import com.server.ScopeServer;
import com.server.SysuserServer;
import com.util.Info;
import com.util.PageBean;

@Controller
public class RecordController {
	@Resource
	private RecordServer recordService;
	@Resource
	private SysuserServer userService;
	@Resource
	private SubjectServer subjectService;
	@Resource
	private ClazzServer clazzService;
	@Resource
	private CourseServer courseService;
	@Resource
	private ScopeServer scopeService;
	@Resource
	private PtypeServer ptypeService;

	@RequestMapping("admin/doAddRecord.do")
	public String doAddRecord(ModelMap map, HttpSession session) {
		Sysuser user = (Sysuser) session.getAttribute("auser");
		if (user == null) {
			return "admin/login";
		} else {
			Map<String, Object> umap = new HashMap<>();
			umap.put("gid", user.getGid());
			map.put("glist", subjectService.getAll(umap));
			return "admin/record_add";
		}
	}

	// 处理更新评价
	@RequestMapping("admin/doUpdateRecord.do")
	public String doUpdateRecord(ModelMap map, int id, HttpSession session) {
		Sysuser user = (Sysuser) session.getAttribute("auser");
		if (user == null) {
			return "admin/login";
		} else {
			Map<String, Object> umap = new HashMap<>();
			umap.put("gid", user.getGid());
			map.put("slist", subjectService.getAll(umap));
			map.put("record", recordService.getById(id));
			return "admin/record_update";
		}
	}

	@RequestMapping("admin/doAddLunWen.do")
	public String doAddLunWen(ModelMap map, int id, HttpSession session) {
		Sysuser user = (Sysuser) session.getAttribute("auser");
		if (user == null) {
			return "admin/login";
		} else {
			Map<String, Object> umap = new HashMap<>();
			umap.put("gid", user.getGid());
			map.put("slist", subjectService.getAll(umap));
			map.put("record", recordService.getById(id));
			return "admin/record_add_lunwen";
		}
	}

	@RequestMapping("admin/doUpdateLunWen.do")
	public String doUpdateLunWen(ModelMap map, int id, HttpSession session) {
		Sysuser user = (Sysuser) session.getAttribute("auser");
		if (user == null) {
			return "admin/login";
		} else {
			Map<String, Object> umap = new HashMap<>();
			umap.put("gid", user.getGid());
			map.put("slist", subjectService.getAll(umap));
			map.put("record", recordService.getById(id));
			return "admin/record_update_lunwen";
		}
	}

	@RequestMapping("admin/doAddChengJi.do")
	public String doAddChenJi(ModelMap map, int id) {
		Map<String, Object> umap = new HashMap<>();
		umap.put("utype", "培训师");
		map.put("ulist", userService.getAll(umap));
		map.put("slist", subjectService.getAll(null));
		map.put("record", recordService.getById(id));
		return "admin/record_chengji_lunwen";
	}

	//TODO
	@RequestMapping("admin/doLookZhiBiao.do")
	public String doLookZhiBiao(ModelMap map, int id) {
		Map<String, Object> umap = new HashMap<>();
		umap.put("utype", "培训师");
		map.put("ulist", userService.getAll(umap));
		map.put("slist", subjectService.getAll(null));
		map.put("record", recordService.getById(id));
		map.put("plist", ptypeService.getAll(null));
		Map<String, Object> smap = new HashMap<>();
		smap.put("rid", id);
		map.put("list", scopeService.getAll(smap));
		return "admin/record_zhibiao";
	}
	
	
	
	@RequestMapping("admin/addRecordChengJi.do")
	public String addRecordChengJi(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, Record record, String upload, HttpSession session) {
		System.out.println("ddddd");
		upload = fileUpload(file, request, upload);
		record.setUpload(upload);
		record.setStatus("成绩");
		recordService.add(record);
		return "redirect:recordList.do";
	}

	@RequestMapping("admin/shenYuanLunWen.do")
	public String shenYuanLunWen(ModelMap map, int id) {
		Map<String, Object> umap = new HashMap<>();
		umap.put("utype", "培训师");
		map.put("ulist", userService.getAll(umap));
		map.put("slist", subjectService.getAll(null));
		map.put("record", recordService.getById(id));
		return "admin/record_shenyue_lunwen";
	}



	@RequestMapping("admin/shenYueLunWen.do")
	public String shenYueLunWen(HttpServletRequest request, Record record, HttpSession session) {
		System.out.println("ddddd");
		recordService.update(record);
		return "redirect:recordList.do";
	}

	// 给职员评成绩
	@RequestMapping("admin/addChengJi.do")
	public String addChengJi(HttpServletRequest request, Record record, HttpSession session) {
		System.out.println("ddddd");
		record.setStatus("已评成绩");
		Record r = recordService.getById(record.getId());
		recordService.update(record);
		Subject subject = subjectService.getById(r.getSid());
		Map<String, Object> smap = new HashMap<>();
		smap.put("sid", subject.getId());
		smap.put("tid", subject.getUid());
		int count = recordService.getCount(smap);
		List<Record> rlist = recordService.getAll(smap);
		double avg = 0.0;
		for (Record rec : rlist) {
			avg += rec.getScope();
		}
		avg = avg / count;
		subject.setStuPj(avg);
		subjectService.update(subject);
		Map<String, Object> tmap = new HashMap<>();
		tmap.put("uid", subject.getUid());
		tmap.put("stype", "课节");
		count = subjectService.getCount(tmap);
		List<Subject> sublist = subjectService.getAll(tmap);
		avg = 0.0;
		for (Subject s : sublist) {
			avg += s.getStuPj();
		}
		avg = avg / count;
		Map<String, Object> pmap = new HashMap<>();
		pmap.put("uid", subject.getUid());
		pmap.put("stype", "课程");
		List<Subject> slist = subjectService.getAll(pmap);
		Subject sub = slist.get(0);
		sub.setStuPj(avg);
		subjectService.update(sub);
		return "redirect:recordList.do";
	}

	// 给培训师评分
	@RequestMapping("admin/updateRecord.do")
	public String updateRecord(ModelMap map, Record record) {
		Record rr = recordService.getById(record.getId());
		recordService.update(record);
		Subject subject = subjectService.getById(rr.getGid());
		Map<String, Object> smap = new HashMap<>();
		smap.put("sid", subject.getId());
		smap.put("tid", subject.getUid());
		int count = recordService.getCount(smap);
		List<Record> rlist = recordService.getAll(smap);
		double avg = 0.0;
		for (Record rec : rlist) {
			avg += rec.getTeaScope();
		}
		avg = avg / count;
		subject.setTeaPj(avg);
		subjectService.update(subject);
		Map<String, Object> tmap = new HashMap<>();
		tmap.put("uid", subject.getUid());
		tmap.put("stype", "课节");
		count = subjectService.getCount(tmap);
		List<Subject> sublist = subjectService.getAll(tmap);
		avg = 0.0;
		for (Subject s : sublist) {
			avg += s.getTeaPj();
		}
		avg = avg / count;
		Sysuser uu = userService.getById(rr.getTid());
		uu.setStatus("已评分");
		Map<String, Object> pmap = new HashMap<>();
		pmap.put("uid", subject.getUid());
		pmap.put("stype", "课程");
		List<Subject> slist = subjectService.getAll(pmap);
		Subject sub = slist.get(0);
		sub.setTeaPj(avg);
		uu.setScope(avg);

		subjectService.update(sub);
		userService.update(uu);
		return "redirect:recordList.do";
	}

	// 保存评分
	@RequestMapping("admin/addRecord.do")//TODO
	public String addRecord(Record record, HttpSession session,String scope,String pids,String zhi) {
		Timestamp time = new Timestamp(System.currentTimeMillis());
		Sysuser u = (Sysuser) session.getAttribute("auser");
		if (u == null) {
			return "admin/login";
		} else {
			/*Map<String, Object> ttmap = new HashMap<>();
			ttmap.put("uid", u.getId());
			ttmap.put("gid", record.getGid());
			int amount = recordService.getCount(ttmap);
			if(amount>0){
				session.setAttribute("info", "您已评价过该实验课知识点！");
				return "admin/error";
			}else{*/
			record.setIsdel("1");
			record.setStatus("待评成绩");
			record.setUid(u.getId());
			Subject subject = subjectService.getById(record.getGid());
			record.setTid(subject.getUid());
			record.setSid(subject.getId());
			record.setCid(subject.getCid());
			record.setScope(0.0);
			double sum = 0.0;
			
			String str [] =scope.split(",");
			for(String s:str){
				System.out.println("scope=="+s);
				sum += Double.parseDouble(s);
			}
			record.setTeaScope(sum);
			String str2 [] =pids.split(",");
			for(String s:str2){
				System.out.println("pid=="+s);
			}
			String str3 [] =zhi.split(",");
			for(String s:str3){
				System.out.println("zhi=="+s);
			}
			
			String no = Info.getID();
			record.setType(no);
			record.setPubtime(time.toString().substring(0, 19));
			recordService.add(record);
			Map<String, Object> smap = new HashMap<>();
			Map<String, Object> smap2 = new HashMap<>();
			smap.put("sid", subject.getId());
			smap2.put("type", no);
			
			smap.put("tid", subject.getUid());
			int count = recordService.getCount(smap);
			List<Record> rlist = recordService.getAll(smap);
			List<Record> rlist2 = recordService.getAll(smap2);
			Record r = rlist2.get(0);
			for(int i=0;i<str.length;i++){
				for(int j=0;j<str2.length;j++){
					System.out.println("i=="+i+"=="+str[i]+"dd");
					System.out.println("j=="+j+"=="+str2[j]+"ee");
					if(i==j){
						System.out.println("i=="+i+"=="+str[i]);
						System.out.println("j=="+j+"=="+str2[j]);
						Scope sco = new Scope();
						sco.setAmount(Double.parseDouble(str[i]));
						sco.setPid(Integer.parseInt(str2[j]));
						sco.setRid(r.getId());
						scopeService.add(sco);
					}
				}
			}
			double avg = 0.0;
			for (Record rec : rlist) {
				avg += rec.getTeaScope();
			}
			avg = avg / count;
			subject.setTeaPj(avg);
			subjectService.update(subject);
			Map<String, Object> tmap = new HashMap<>();
			tmap.put("uid", subject.getUid());
			tmap.put("stype", "课节");
			count = subjectService.getCount(tmap);
			List<Subject> sublist = subjectService.getAll(tmap);
			avg = 0.0;
			for (Subject s : sublist) {
				avg += s.getTeaPj();
			}
			avg = avg / count;
			Sysuser uu = userService.getById(subject.getUid());
			uu.setStatus("已评分");
			Map<String, Object> pmap = new HashMap<>();
			pmap.put("uid", subject.getUid());
			pmap.put("stype", "课程");
			List<Subject> slist = subjectService.getAll(pmap);
			Subject sub = slist.get(0);
			sub.setTeaPj(avg);
			uu.setScope(avg);

			subjectService.update(sub);
			userService.update(uu);
			return "admin/success";
			}
		/*}*/

	}

	// 查询所有评价的信息
	@RequestMapping("admin/recordList.do")
	public String userList(@RequestParam(value = "page", required = false) String page, HttpSession session,
			ModelMap map) {
		Sysuser u = (Sysuser) session.getAttribute("auser");
		if (u == null) {
			return "admin/login";
		} else {
			if (page == null || page.equals("")) {
				page = "1";
			}
			PageBean pageBean = new PageBean(Integer.parseInt(page), PageBean.PAGESIZE);
			Map<String, Object> pmap = new HashMap<String, Object>();
			pmap.put("pageno", pageBean.getStart());
			pmap.put("pageSize", pageBean.getPageSize());
			Map<String, Object> cmap = new HashMap<String, Object>();
			if (u.getUtype().equals("职员")) {
				pmap.put("uid", u.getId());
				cmap.put("uid", u.getId());
			} else if (u.getUtype().equals("培训师")) {
				pmap.put("tid", u.getId());
				cmap.put("tid", u.getId());
			} else if (u.getUtype().equals("管理员")) {
				pmap.put("uid", null);
				cmap.put("uid", null);
			}
			int total = recordService.getCount(cmap);
			/*
			 * if(total==0&&u.getUtype().equals("职员")){ return
			 * "redirect:doAddRecord.do"; }else{
			 */
			pageBean.setTotal(total);
			List<Record> list = recordService.getByPage(pmap);
			map.put("page", pageBean);
			map.put("list", list);
			Map<String, Object> umap = new HashMap<>();
			Map<String, Object> umap2 = new HashMap<>();
			Map<String, Object> smap = new HashMap<>();
			umap.put("utype", "职员");
			umap2.put("utype", "培训师");
			smap.put("stype", "课节");
			map.put("slist", subjectService.getAll(smap));
			map.put("stulist", userService.getAll(umap));
			map.put("tealist", userService.getAll(umap2));
			
			map.put("clist", courseService.getAll(null));
			map.put("glist", clazzService.getAll(null));
			session.setAttribute("p", 1);
			return "admin/record_list";
			/* } */

		}
	}

	// 模糊查询并分页
	@RequestMapping("admin/recordListQuery.do")
	public String useListQuery(@RequestParam(value = "page", required = false) String page, HttpSession session,
			ModelMap map, Record rec) {
		Sysuser u = (Sysuser) session.getAttribute("auser");
		if (u == null) {
			return "admin/login";
		} else {
			if (page == null || page.equals("")) {
				page = "1";
			}
			PageBean pageBean = new PageBean(Integer.parseInt(page), PageBean.PAGESIZE);
			Map<String, Object> pmap = new HashMap<String, Object>();
			pmap.put("pageno", pageBean.getStart());
			pmap.put("pageSize", pageBean.getPageSize());
			Map<String, Object> cmap = new HashMap<String, Object>();
			if (u.getUtype().equals("职员")) {
				pmap.put("uid", u.getId());
				cmap.put("uid", u.getId());
				if (rec.getTid() != null && !rec.getTid().equals("")) {
					pmap.put("tid", rec.getTid());
					cmap.put("tid", rec.getTid());
				} else {
					pmap.put("tid", null);
					cmap.put("tid", null);
				}
			} else if (u.getUtype().equals("培训师")) {
				pmap.put("tid", u.getId());
				cmap.put("tid", u.getId());
				if (rec.getUid() != null && !rec.getUid().equals("")) {
					pmap.put("uid", rec.getUid());
					cmap.put("uid", rec.getUid());
				} else {
					pmap.put("uid", null);
					cmap.put("uid", null);
				}
			} else if (u.getUtype().equals("管理员")) {
				if (rec.getTid() != null && !rec.getTid().equals("")) {
					pmap.put("tid", rec.getTid());
					cmap.put("tid", rec.getTid());
				} else {
					pmap.put("tid", null);
					cmap.put("tid", null);
				}
				if (rec.getUid() != null && !rec.getUid().equals("")) {
					pmap.put("uid", rec.getUid());
					cmap.put("uid", rec.getUid());
				} else {
					pmap.put("uid", null);
					cmap.put("uid", null);
				}
			}
			if (rec.getGid() != null && !rec.getGid().equals("")) {
				pmap.put("gid", rec.getGid());
				cmap.put("gid", rec.getGid());
			} else {
				pmap.put("gid", null);
				cmap.put("gid", null);
			}

			int total = recordService.getCount(cmap);
			pageBean.setTotal(total);
			List<Record> list = recordService.getByPage(pmap);
			map.put("page", pageBean);
			map.put("list", list);
			Map<String, Object> umap = new HashMap<>();
			Map<String, Object> umap2 = new HashMap<>();
			Map<String, Object> smap = new HashMap<>();
			umap.put("utype", "职员");
			umap2.put("utype", "培训师");
			map.put("stulist", userService.getAll(umap));
			map.put("tealist", userService.getAll(umap2));
			smap.put("stype", "课节");
			map.put("slist", subjectService.getAll(smap));
			map.put("clist", courseService.getAll(null));
			session.setAttribute("p", 2);
			return "admin/record_list";
		}
	}

	@RequestMapping("admin/deleteRecord.do")
	public String deleteRecord(int id) {
		recordService.delete(id);
		return "redirect:recordList.do";
	}

	// 文件上传
	public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, String img) {
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		// String path1="H:\\workspace\\pingjia\\WebRoot\\upload\\";
		File targetFile = new File(path, fileName);
		// File targetFile1 = new File(path1, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
			// file.transferTo(targetFile1);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String pa = request.getContextPath() + "/upload/" + fileName;
		System.out.println("path===" + pa);
		if (fileName != null && !fileName.equals("")) {
			img = fileName;
		} else {
			img = null;
		}
		return img;

	}

}
